// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { RvoPolygon } from "./libs/Obstacle";
import { RVOSimulator } from "./libs/RVOSimulator";
import { Vector2 } from "./libs/Vector2";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ObstacleComp extends cc.Component {
    private _isGray: boolean = false;
    private _rvoPolygon: RvoPolygon;
    protected onLoad(): void {
        this.addObstacle();
    }

    protected onEnable(): void {
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    protected onDisable(): void {
        this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    private onTouchEnd() {
        this._isGray = !this._isGray;
        this.setGray(this._isGray);

        this._isGray ? this.removeObstacle() : this.addObstacle();
    }

    private setGray(isGray: boolean) {
        let sprite = this.node.getComponent(cc.Sprite);
        if (this._isGray) {
            sprite.setMaterial(0, cc.MaterialVariant.getBuiltinMaterial("2d-gray-sprite"));
        } else {
            sprite.setMaterial(0, cc.MaterialVariant.getBuiltinMaterial("2d-sprite"));
        }
    }

    private addObstacle() {
        let box = this.node.getBoundingBox();
        this._rvoPolygon = RVOSimulator.getInstance().addObstacle([
            new Vector2(box.x, box.y),
            new Vector2(box.xMax, box.y),
            new Vector2(box.xMax, box.yMax),
            new Vector2(box.x, box.yMax),
        ]);
    }

    private removeObstacle() {
        if (this._rvoPolygon) {
            RVOSimulator.getInstance().removeObstacle(this._rvoPolygon);
            this._rvoPolygon = null;
        }
    }

    protected onDestroy(): void {
        this.removeObstacle();
    }
}
